package game.module.user.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.DaoCommonHandler;
import game.db.DataSourceManager;
import game.module.user.bean.Activity_stateBean;

public class Activity_stateDao {

	private static Logger logger = LoggerFactory.getLogger(Activity_stateDao.class);

	private DataSource dataSource = DataSourceManager.getInstance().getDataSource();

	static class SingletonHolder {

		static Activity_stateDao instance = new Activity_stateDao();
	}

	public static Activity_stateDao getInstance() {

		return SingletonHolder.instance;
	}

	private ResultSetHandler<Activity_stateBean> A_activatyHandler = new ResultSetHandler<Activity_stateBean>() {

		@Override
		public Activity_stateBean handle(ResultSet rs) throws SQLException {
			Activity_stateBean activitybean = null;
			if (rs.next()) {
				activitybean = new Activity_stateBean();
				activitybean.setId(rs.getInt("id"));
				activitybean.setPlayerId(rs.getInt("playerId"));
				activitybean.setTurntable_state(rs.getBoolean("turntable_state"));
				activitybean.setLogin_time(rs.getDate("login_time"));
			}
			return activitybean;
		}

	};

	// 获得一个玩家的数据
	public Activity_stateBean getActivityById(int playerId) {
		Activity_stateBean ret = null;
		QueryRunner runner = new QueryRunner(dataSource);
		try {
			ret = runner.query("SELECT * from activity_state where playerId = ?", A_activatyHandler, playerId);
		} catch (SQLException e) {
			logger.error("", e);
			return ret;
		}
		return ret;
	}

	// 更新玩家数据
	public void updateActivity(Activity_stateBean activitybean) {
		QueryRunner runner = new QueryRunner(dataSource);

		try {
			runner.update("update activity_state set turntable_state=? login_time=? where id = ?", activitybean.isTurntable_state(),
					activitybean.getId(),activitybean.getLogin_time());
		} catch (SQLException e) {
			logger.error("", e);
		}
	}

	//
	public boolean addActivity(Activity_stateBean activitybean) {
		logger.info("add activity");
		boolean addRet = false;
		QueryRunner runner = new QueryRunner(dataSource);
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			int ret = runner.update(conn, "insert into activity_state(playerId,turntable_state,login_time)" + "values(?,?,?)",
					activitybean.getPlayerId(), activitybean.isTurntable_state(),activitybean.getLogin_time());
			if (ret > 0) {
				addRet = true;
			}
			if (addRet) {
				int theId = runner.query(conn, "SELECT LAST_INSERT_ID();", DaoCommonHandler.Integerhandler);
				activitybean.setId(theId);
			}
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return addRet;

	}

}
